//
//  MyUtilities.m
//  ZingBrowser
//
//  Created by -Xh- on 1/15/13.
//  Copyright (c) 2013 -Xh-. All rights reserved.
//

#import "MyUtilities.h"
#import "StaticVariables.h"
@implementation MyUtilities


+(void)logArray:(NSArray *)_array withTitle:(NSString *)_title{
    NSLog(@"===%@===",_title);
    for(int i=0;i<_array.count;i++){
        NSString* currentString=(NSString*)[_array objectAtIndex:i];
        NSLog(@"%@",currentString);
    }
}

+(NSString*)copyDatabaseToDocumentFolder:(NSString *)_dbName{
    NSArray* documentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentDir=[documentPaths objectAtIndex:0];
    NSString* databasePath=[documentDir stringByAppendingString:_dbName];
    NSFileManager* fileManager=[NSFileManager defaultManager];
    bool success= [fileManager fileExistsAtPath:databasePath];
    if(success) return databasePath;
    NSString* databasePathFromApp=[[[NSBundle mainBundle]resourcePath] stringByAppendingString:_dbName];
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    return databasePath;
}

+(NSString *)getGeneratedIDWithPrefix:(NSString *)_prefix AndIndex:(int)_index WithMaxNumberOfZero:(int)_maxNumOfZero{
    NSString* indexString=[NSString stringWithFormat:@"%i",_index];
    int numOfZero=_maxNumOfZero-indexString.length;
    NSString* zeroString=@"";
    for(int i=0;i<numOfZero;i++){
        zeroString = [zeroString stringByAppendingString:@"0"];
    }
    NSString* resultString=[NSString stringWithFormat:@"%@%@%@",_prefix,zeroString,indexString];
    return resultString;
}

+(UIEdgeInsets)getEdgeInsetFromRect:(CGRect)rect{
    double left=rect.origin.x;
    double top=rect.origin.y;
    double right=rect.origin.x+rect.size.width;
    double bottom=rect.origin.y+rect.size.height;
    return UIEdgeInsetsMake(top, left, bottom, right);

}

+(BOOL)rect:(CGRect)_rect1 isEqualToRect:(CGRect)_rect2{
    return (_rect1.origin.x==_rect2.origin.x
            && _rect1.origin.y==_rect2.origin.y
            && _rect1.size.width==_rect2.size.width
            && _rect1.size.height==_rect2.size.height);
}

+(UIImage *)takeScreenShotOfView:(UIView *)_view WithOffset:(CGPoint)_offset{
    //    uint64_t start = mach_absolute_time();
    // Your code here, loop here, anything to process
    
    UIGraphicsBeginImageContext(CGSizeMake(_view.bounds.size.width, _view.bounds.size.height-_offset.y));
     
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, 0, _offset.x);
    [_view.layer renderInContext:c];
    UIImage *screenShotimage = UIGraphicsGetImageFromCurrentImageContext();
    //UIImageWriteToSavedPhotosAlbum(screenShotimage, nil, nil, nil);
    UIGraphicsEndImageContext();
    return  screenShotimage;
}

+(UIImage *)takeScreenShotOfView:(UIView *)_view{
    //    uint64_t start = mach_absolute_time();
    // Your code here, loop here, anything to process
    
    UIGraphicsBeginImageContext(CGSizeMake(_view.bounds.size.width, _view.bounds.size.height));
    
    CGContextRef c = UIGraphicsGetCurrentContext();

    [_view.layer renderInContext:c];
    UIImage *screenShotimage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    return  screenShotimage;
}

+(UIImage *)takeScreenShotOfTheWholeScreen{
    // Create a graphics context with the target size
    // On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
    // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    if (NULL != UIGraphicsBeginImageContextWithOptions)
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    else
        UIGraphicsBeginImageContext(imageSize);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // Iterate over every window from back to front
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
        {
            // -renderInContext: renders in the coordinate space of the layer,
            // so we must first apply the layer's geometry to the graphics context
            CGContextSaveGState(context);
            // Center the context around the window's anchor point
            CGContextTranslateCTM(context, [window center].x, [window center].y);
            // Apply the window's transform about the anchor point
            CGContextConcatCTM(context, [window transform]);
            // Offset by the portion of the bounds left of and above the anchor point
            CGContextTranslateCTM(context,
                                  -[window bounds].size.width * [[window layer] anchorPoint].x,
                                  -[window bounds].size.height * [[window layer] anchorPoint].y);
            
            // Render the layer hierarchy to the current context
            [[window layer] renderInContext:context];
            
            // Restore the context
            CGContextRestoreGState(context);
        }
    }
    
    // Retrieve the screenshot image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}
+(UIImage *)takeScreenShotOfTheWholeScreenWithOffset:(CGPoint)_offset{
    
    UIImage* wholeScreenImage=[self takeScreenShotOfTheWholeScreen];
    CGSize wholeSize=wholeScreenImage.size;
    //double screenHeight=
    CGRect clippedRect  = CGRectMake(0, _offset.x, wholeSize.width, wholeSize.height-_offset.y- _offset.x);
    CGImageRef imageRef = CGImageCreateWithImageInRect([wholeScreenImage CGImage], clippedRect);
    UIImage *newImage   = [UIImage imageWithCGImage:imageRef];
    CGSize newSize=newImage.size;
    CGImageRelease(imageRef);
    return newImage;
     
    
}

+(NSString *)getCorrectDateFormatFromDate:(NSDate *)_date{
    NSString* originalDateString=[NSString stringWithFormat:@"%@",_date];
    NSString* correctDateString=[originalDateString stringByReplacingOccurrencesOfString:@" +0000" withString:@""];
    return correctDateString;
}

+(void)logRect:(CGRect)rect withTag:(NSString *)tag{
    NSLog(@"%@ : %0.0f %0.0f | %0.0f %0.0f",tag,rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
}
+(void)logScrollView:(UIScrollView *)_scrollView withTag:(NSString *)_tag{
    NSLog(@"%@",_tag);
    for(int i=0;i<_scrollView.subviews.count;i++){
        NSString*  className= NSStringFromClass([[_scrollView.subviews objectAtIndex:i] class]);
        NSLog(@"[%i] : %@",i,className);
    }
    NSLog(@"----------------");
}
+(void)logPoint:(CGPoint)point withTag:(NSString *)tag{
    NSLog(@"%@ : %0.1f %0.1f",tag,point.x,point.y);
}
+(void)logSize:(CGSize)size withTag:(NSString *)tag{
     NSLog(@"%@ : %0.0f %0.0f",tag,size.width,size.height);
}

+(UIImage*)getImageWithURL:(NSString*)_url FromDict:(NSMutableDictionary*) imageDict{
   return [imageDict objectForKey:_url];

}


+(NSString *)getLocalizeStringFromTag:(NSString *)_tagName{
    NSString* languageCode = [[[StaticVariables shareVariables]userDefaults] getLanguageString];
    //NSString* languageCode = [[[[StaticVariables shareVariables]settingsData]languageValues]objectAtIndex:languageIndex];
    NSString *path= [[NSBundle mainBundle] pathForResource:languageCode ofType:@"lproj"];
    NSBundle* languageBundle = [NSBundle bundleWithPath:path];
    return [languageBundle localizedStringForKey:_tagName value:nil table:nil];
}

+(int)randomWithMin:(int)_min AndMax:(int)_max{
    int randomNumber = ( rand()%(_max-_min) ) + _min;
    return randomNumber;
}

+(NSString *)getLocalizeErrorMessageFromError:(NSError *)error{
    NSString* resultString;
    int currentLanguage = [[[[StaticVariables shareVariables]userDefaults]language] intValue];
    if(currentLanguage == 0){
        switch (error.code) {
            case NSURLErrorNotConnectedToInternet:
                resultString = [self getLocalizeStringFromTag:@"ErrorNoInternet"];
                break;
                
            case NSURLErrorTimedOut:
                resultString = [self getLocalizeStringFromTag:@"ErrorTimedOut"];
                break;
                
            case NSURLErrorUnsupportedURL:
                resultString = [self getLocalizeStringFromTag:@"ErrorUnsupportURL"];
                break;
                
            case NSURLErrorNetworkConnectionLost:
                resultString = [self getLocalizeStringFromTag:@"ErrorConnectionLost"];
                break;
                
            case NSURLErrorUnknown:
                resultString = [self getLocalizeStringFromTag:@"ErrorUnknown"];
                break;
            case NSURLErrorBadURL:
                resultString = [self getLocalizeStringFromTag:@"ErrorBadURL"];
                break;
                
            case NSURLErrorCannotFindHost:
                resultString = [self getLocalizeStringFromTag:@"ErrorCannotFindHost"];
                break;
                
            case NSURLErrorCannotConnectToHost:
                resultString = [self getLocalizeStringFromTag:@"ErrorCannotConnectToHost"];
                break;
                
            case NSURLErrorResourceUnavailable:
                resultString = [self getLocalizeStringFromTag:@"ErrorCannotResourceNotAvailable"];
                break;
                
            case NSURLErrorBadServerResponse:
                resultString = [self getLocalizeStringFromTag:@"ErrorCannotBadServerResponse"];
                break;
            default:
                resultString = error.localizedDescription;
                break;
        }
    }else{
        resultString = error.localizedDescription;
    }
    
    return resultString;
}

+(void)logAllScrollViewFromParentView:(UIView *)parentView{
    for(int i=0;i<parentView.subviews.count;i++){
        UIView* iChildView = [parentView.subviews objectAtIndex:i];
        if([iChildView isKindOfClass:[UIScrollView class]]){
            UIScrollView* iScrollView = (UIScrollView*)iChildView;
            NSLog(@"%@ - scrollView.scrollsToTop = %@",NSStringFromClass([parentView class]),iScrollView.scrollsToTop ? @"YES" : @"NO");
            for(int j=0;j<iScrollView.subviews.count;j++){
                [self logAllScrollViewFromParentView:[iScrollView.subviews objectAtIndex:j]];
            }
        }else{
            if([iChildView isKindOfClass:[UIWebView class]]){
                UIWebView* iWebView = (UIWebView*)iChildView;
                NSLog(@"%@ - webView - scrollView.scrollsToTop = %@",NSStringFromClass([parentView class]),iWebView.scrollView.scrollsToTop ? @"YES" : @"NO");
                
            }else{
                [self logAllScrollViewFromParentView:iChildView];

            }
        }
    }
}
+ (void)listSubviewsOfView:(UIView *)view {
    
    // Get the subviews of the view
    NSArray *subviews = [view subviews];
    
    // Return if there are no subviews
    if ([subviews count] == 0) return;
    
    for (UIView *subview in subviews) {
        if([subview isKindOfClass:[UIScrollView class]]){
            UIScrollView* iScrollView = (UIScrollView*)subview;
            NSLog(@"%@ - scrollToTop = %@", subview,iScrollView.scrollsToTop ? @"YES" : @"NO");
        }
        
        
        // List the subviews of subview
        [self listSubviewsOfView:subview];
    }
}
@end
